package com.itheima.advice;

import com.itheima.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAdvice {
    //注入
    @Autowired
    public LogService logService;

    @Pointcut("execution(* com.itheima.service.AccountService.transfer(..))")
    public void pt(){}

    @Around("pt()")
    public Object arounds(ProceedingJoinPoint pjp){
        Object[] args = pjp.getArgs();
        String out = args[1].toString();
        String in = args[1].toString();
        Double money = Double.parseDouble(args[2].toString());

        Object proceed = null;
        try {
            proceed = pjp.proceed();
            String info = "转账成功";
            System.out.println(info);
            logService.log(out,in,money,info);
        } catch (Throwable e) {
            String info = "转账失败" + e.getMessage();
            System.out.println(info);
            logService.log(out,in,money,info);

            //因为环绕通知已经把异常处理了，这里要手动生成一个异常

            throw new RuntimeException(info);
        }
        System.out.println("转账操作完成");
        return null;
    }

    /*@AfterReturning(value = "pt()",returning = "obj")
    public void runing(JoinPoint point , Object obj){
        Object[] args = point.getArgs();
        String out = args[1].toString();
        String in = args[1].toString();
        Double money = Double.parseDouble(args[2].toString());

        String info = "转账成功";
        System.out.println(info);
        logService.log(out,in,money,info);
    }

    @AfterThrowing(value = "pt()" , throwing = "t")
    public void throwing(JoinPoint point , Throwable t){
        Object[] args = point.getArgs();
        String out = args[1].toString();
        String in = args[1].toString();
        Double money = Double.parseDouble(args[2].toString());

        String info = "转账失败" + t.getMessage();
        System.out.println(info);
        logService.log(out,in,money,info);
    }*/
}
